package com;

import java.io.IOException;
import java.util.ConcurrentModificationException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Transaction;

@SuppressWarnings("serial")
public class CreateAccountServlet extends HttpServlet 
{//client-server style (get input from client, then redirect output)
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException 
	{
		
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		String msg = "";
		String username = req.getParameter("username");
		String pw = req.getParameter("password");
		String first = req.getParameter("firstName");
		String last = req.getParameter("lastName");
		String credit = req.getParameter("credit");
		String type = req.getParameter("type"); 
		
		
		
		//buyer and sellers are determined by whether rating and ratingcount are null or not
		if(type==null || username.isEmpty()){
			//auction has expired
			msg = "Error. Please fill in all fields.";
			req.setAttribute("msg", msg);

			
			System.out.println(msg);

			req.getRequestDispatcher("error.jsp").forward(req, resp);
		}else{
				
			
			for (int j = 0; j < 10; j++) {
				Transaction tx = ds.beginTransaction();
				try {
					
					Entity e = new Entity("User", username);
					e.setProperty("PASSWORD", pw);
					e.setProperty("FIRSTNAME", first);
					e.setProperty("LASTNAME", last);
					e.setProperty("CREDIT", credit);
					e.setProperty("TYPE", type);
					//Blackboard style
					ds.put(tx, e);
					tx.commit();
					break;
					
					
				} catch (ConcurrentModificationException ed) {
					// continue
				} finally {
					if (tx.isActive())
						tx.rollback();
				}
			}
			req.getRequestDispatcher("index.html").forward(req, resp);
		}
		
	}
}
